package com.system.module.system.controller;

import com.aliyun.oss.ServiceException;
import com.system.common.utils.SecurityUtils;
import com.system.common.utils.ServletUtils;
import com.system.framework.aspect.lang.annotation.Log;
import com.system.framework.aspect.lang.enums.BusinessType;
import com.system.framework.security.LoginUser;
import com.system.framework.security.service.TokenService;
import com.system.framework.web.controller.BaseController;
import com.system.framework.web.domain.Result;
import com.system.module.oss.service.IUploadService;
import com.system.module.system.entity.SysUser;
import com.system.module.system.service.ISysUserService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 个人信息 业务处理
 *
 * @author 程序员Mars
 */
@RestController
@RequestMapping("/system/user/profile")
@AllArgsConstructor
public class SysProfileController extends BaseController {

    private final ISysUserService userService;

    private final IUploadService uploadService;

    private final TokenService tokenService;

    /**
     * 个人信息
     */
    @GetMapping
    public Result profile() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        Result ajax = Result.success(user);
        ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        return ajax;
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public Result updateProfile(@RequestBody SysUser user) {
        if (userService.updateUserProfile(user) > 0) {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            // 更新缓存用户信息
            loginUser.getUser().setNickName(user.getNickName());
            loginUser.getUser().setPhonenumber(user.getPhonenumber());
            loginUser.getUser().setEmail(user.getEmail());
            loginUser.getUser().setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return Result.success();
        }
        return Result.error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public Result updatePwd(String oldPassword, String newPassword) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return Result.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return Result.error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0) {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return Result.success();
        }
        return Result.error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public Result avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new ServiceException("请上传文件");
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String avatar = uploadService.upload(file);
        if (userService.updateUserAvatar(loginUser.getUsername(), avatar)) {
            Result ajax = Result.success();
            ajax.put("imgUrl", avatar);
            // 更新缓存用户头像
            loginUser.getUser().setAvatar(avatar);
            tokenService.setLoginUser(loginUser);
            return ajax;
        }
        return Result.error("上传图片异常，请联系管理员");
    }
}
